package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MutableCallSite;

@RestController
@RequestMapping("/test")
public class TestController {
    //@RequestMapping(value = "/hi",method = RequestMethod.POST)
    @GetMapping("/hi")
    //@PostMapping("/hi")
    public String SaiHi(@RequestParam(value = "time",required = false) String name) {
        return "Hello SpringMVC  " + name;
    }

    @GetMapping("/get-user")
    public String getUser(@RequestBody User user) {
        return user.toString();
    }

    @GetMapping("/url/{name}/{password}")
    public String getUrl(@PathVariable("name") String name, @PathVariable("password") String password) {
        return name + password;
    }

    //文件上传
    @RequestMapping("/upfile")
    public String upFile(@RequestPart("myfile")MultipartFile file) throws IOException {
        String path = "D://test//img.png";
        file.transferTo(new File(path));
        return path;

    }

    //存储和获取session

    @RequestMapping("/sets")
    public String setSession(HttpServletRequest req) {
        HttpSession session = req.getSession();
        session.setAttribute("user","user");
        return " set session success";
    }

    @RequestMapping("/gets")
    public String getSession(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if(session!= null && session.getAttribute("user")!=null) {
            return (String) session.getAttribute("user");
        }else {
            return "No Session";
        }

    }

    //使用注解
    @RequestMapping("/sess2")
    public String getSession2(@SessionAttribute(value = "user",required = false) String username) {
        return "username: " + username;
    }
}
